﻿///////////////////////////////////////////////////////////////////////////////////
/// 文 件 名: NeedsOfBorrowerForm.cs
/// 作    者: XXD
/// 创建日期: 2012/6/18 9:48:18
/// 
///---------------------------------修改记录--------------------------------------
/// 修 改 人:          
/// 修改日期:
/// 修改原因: 
//////////////////////////////////////////////////////////////////////////////////
namespace ZX.WebApp.WorkFlow.CustomForms
{
    using System;
    using ZX.BPM.Library;
    using ZX.Web.UI.Controls;
    using DevExpress.Web.ASPxEditors;

    /// <summary>
    /// (借款，需求，报销)申请单页面
    /// </summary>
    public partial class NeedsOfBorrowerForm : EditUIPage
    {
        #region 事件处理

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Session["User"] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            if (!this.IsPostBack)
            {
                this.Session["NeedsOfBorrower" + strWorkflowInsId] = null;

                NeedsOfBorrowerEdit entity = GetNeedsOfBorrowerEdit();
                //设置数据源
                NeedsOfBorrower.Bind(entity, true);
                NeedsOfBorrower.DataBind();
            }

            NeedsOfBorrowerEdit tempEntity = GetNeedsOfBorrowerEdit();
            NeedsOfBorrower.InitFileUploader(tempEntity);

            //设置采购单信息
            MaterialsProcurementDetail.DataSource = tempEntity;
            try
            {
                MaterialsProcurementDetail.DataBind();
            }catch(Exception ex){
            }
            if (Status == "3")
            {
                NeedsOfBorrower.ReadOnly = true;
                MaterialsProcurementDetail.ReadOnly = true;
                btnSubmit.Enabled = false;
            }
            else if (Status == "2")
            {
                btnDraft.Enabled = false;
            }
        }

        public void btnSubmit_Click(object sender, EventArgs e)
        {
            ErrorLable.Text = string.Empty;

            NeedsOfBorrowerEdit data = (NeedsOfBorrowerEdit)this.Session["NeedsOfBorrower" + strWorkflowInsId];
            if (data == null)
            {
                return;
            }

            try
            {
                CrmWorkFlowService.WorkFlowServiceClient wfClient = new CrmWorkFlowService.WorkFlowServiceClient();
                NeedsOfBorrower.Bind(data, false);

                ASPxButton button = (ASPxButton)sender;
                bool isDraft = false;

                if (button.Text.Equals("草稿"))
                {
                    isDraft = true;
                }


                //设置控件数据到对象
                if (data.IsNew)
                {
                    data.No = wfClient.GetWorkFlowNO();

                    //保存数据
                    SaveNeedsOfBorrower(data);

                    //启动流程
                    string result = wfClient.Start(
                        this.User.LoginName,
                        data.WorkFlowId,
                        data.WorkTaskId,
                        data.WorkFlowInsId,
                        data.WorkTaskInsId,
                        data.No,
                        "提交",
                        "3",
                        data.Subject,
                        isDraft);
                }
                else
                {
                    //保存数据
                    SaveNeedsOfBorrower(data);

                    SaveUserControlApp(
                    this.User.UserID.ToString(),
                    this.User.UName,
                    this.EmpPropertyValues.DeptName,
                    this.EmpPropertyValues.PostName,
                    strOperatorInstanceId,
                    strWorkFlowId,
                    strWorkflowInsId,
                    strWorkTaskId,
                    strWorkTaskInsId);

                    Submit(
                        this.User.LoginName,
                        strOperatorInstanceId,
                        "提交");
                }

                if (!isDraft)
                {
                    //跳转到提示页面
                    Response.Redirect(@"../../Crm/BasePages/tooltip.aspx?WorkTaskInstanceId=" + data.WorkTaskInsId);
                    Response.Close();
                }
                else
                {
                    btnDraft.Enabled = false;
                    ASPxLabel2.Text = "草稿保存成功!";
                }
            }
            catch (Exception ex)
            {
                ZX.BLL.Extend.LogBusiness.WriteExceptionLog(ex, this.User);
                ShowError(ex.Message);
            }
        }

        private string CreateWorkTaskTitle(string flowCaption)
        {
            string _title =  flowCaption + "-" + this.EmpPropertyValues.Proposer + "-" + "[" + DateTime.Now.ToString("yyyy-MM-dd hh:ss:mm") + "]";
            return _title;
        }

        public void btnClose_Click(object sender, EventArgs e)
        {
            Response.Close();
        }

        #endregion

        #region 查询串参数

        public string Status
        { get { return this.GetStringFromQueryString("statues", ""); } }

        public string IsDraft
        { get { return this.GetStringFromQueryString("statues", ""); } }

        /// <summary>
        /// 
        /// </summary>
        public string strWorkFlowId
        {
            get
            {
                string wtid = this.GetStringFromQueryString("WorkflowId", "");
                if (wtid == "")
                {
                    wtid = this.GetStringFromQueryString("wfid", "");
                }
                return wtid;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public string strWorkTaskId
        {
            get
            {
                string wfid = this.GetStringFromQueryString("WorktaskId", "");
                if (wfid == "")
                {
                    wfid = this.GetStringFromQueryString("wtid", "");
                }
                return wfid;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        public string strOperatorInstanceId
        { get { return this.GetStringFromQueryString("OperatorInstanceId", ""); } }
        /// <summary>
        /// 
        /// </summary>
        public string strWorkflowInsId
        { get { return this.GetStringFromQueryString("WorkflowInsId", ""); } }
        /// <summary>
        /// 
        /// </summary>
        public string strWorkTaskInsId
        { get { return this.GetStringFromQueryString("WorktaskInsId", ""); } }

        public string strView
        { get { return this.GetStringFromQueryString("view", ""); } }
        public string strOperStatus
        { get { return this.GetStringFromQueryString("OperStatus", ""); } }
        public string strDescript
        { get { return this.GetStringFromQueryString("descript", ""); } }

        #endregion

        #region 本地方法

        private NeedsOfBorrowerEdit GetNeedsOfBorrowerEdit()
        {
            NeedsOfBorrowerEdit businessObject = (NeedsOfBorrowerEdit)Session["NeedsOfBorrower" + strWorkflowInsId];
            if (businessObject == null)
            {
                try
                {
                    //string idString = Request.QueryString["id"];
                    if (!string.IsNullOrEmpty(strWorkflowInsId))
                    {
                        // Guid id = new Guid(strWorkflowInsId);
                        businessObject = NeedsOfBorrowerEdit.Get(strWorkflowInsId);
                        //businessObject.WorkTaskInsId = strWorkTaskInsId;
                        //businessObject.WorkTaskId = strWorkTaskId;
                    }
                    else
                    {
                        businessObject = NeedsOfBorrowerEdit.New();
                        businessObject.CreatedTime = DateTime.Now.ToShortDateString();
                        businessObject.Proposer = base.User.UName;
                        businessObject.PostName = base.EmpPropertyValues.PostName;
                        businessObject.Filiale = base.EmpPropertyValues.Filiale;
                        businessObject.DeptName = base.EmpPropertyValues.DeptName;
                      
                        //businessObject.Proposer = "admin";
                        //businessObject.PostName = "admin";
                        //businessObject.Filiale = "admin";
                        //businessObject.DeptName = "admin";
                        businessObject.ReimbursementMode = "";
                        businessObject.ReimbursementType = "";
                        businessObject.Remarks = "";
                        businessObject.WorkFlowId = this.GetStringFromQueryString("wfid", "");
                        businessObject.WorkTaskId = this.GetStringFromQueryString("wtid", "");
                        businessObject.WorkFlowInsId = Guid.NewGuid().ToString();
                        businessObject.WorkTaskInsId = Guid.NewGuid().ToString();

                        CrmWorkFlowService.WorkFlowServiceClient wfClient = new CrmWorkFlowService.WorkFlowServiceClient();
                        string flowCaption = wfClient.GetWorkFlowCaption(strWorkFlowId);
                        string tilte = CreateWorkTaskTitle(flowCaption);
                        businessObject.Subject = tilte;
                    }
                    Session["NeedsOfBorrower" + strWorkflowInsId] = businessObject;
                }
                catch (System.Security.SecurityException ex)
                {
                    throw ex;
                }
            }

            return businessObject;
        }

        private void SaveNeedsOfBorrower(NeedsOfBorrowerEdit needsOfBorrower)
        {
            try
            {
                MaterialsProcurementDetail.EndEdit();

                if (needsOfBorrower.BrokenRulesCollection.Count > 0)
                {
                    return;
                }

                Session["NeedsOfBorrower" + strWorkflowInsId] = needsOfBorrower.Save();
            }
            catch (Csla.Validation.ValidationException ex)
            {
                System.Text.StringBuilder message = new System.Text.StringBuilder();
                message.AppendFormat("{0}", ex.Message);
                if (needsOfBorrower.BrokenRulesCollection.Count > 0)
                {
                    message.Append("<ul>");
                    foreach (Csla.Validation.BrokenRule rule in needsOfBorrower.BrokenRulesCollection)
                        message.AppendFormat("<li>{0}: {1}</li>", rule.Property, rule.Description);
                    message.Append("</ul>");
                }
                ShowError(message.ToString());
            }
            catch (Csla.DataPortalException ex)
            {
                ShowError(ex.BusinessException.Message);
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
        }

        private void ShowError(string error)
        {
            this.ErrorLable.Text = error;
        }

        #endregion

        #region 外部接口
        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle
        {
            get
            {
                return Request["title"].ToString();
            }
        }


        public void Submit(string userID, string operatorInstanceId, string commandName)
        {
            //启动流程
            CrmWorkFlowService.WorkFlowServiceClient wfClient = new CrmWorkFlowService.WorkFlowServiceClient();

            wfClient.TaskClaim(userID, operatorInstanceId);   // 认领操作

            if (commandName.Equals("提交"))
            {
                wfClient.Run(userID, operatorInstanceId, commandName);
            }
            else
            {
                wfClient.TaskBackApplicant(userID, operatorInstanceId);
            }
            //跳转到提示页面
            // Response.Redirect(@"../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + operatorInstanceId);

        }


        /// <summary>
        /// 保存审批意见
        /// </summary>
        public void SaveUserControlApp(
            string userID,
            string userName,
            string userDept,
            string userPost,
            string operatorInsId,
            string workflowId,
            string workflowInsId,
            string worktaskId,
            string worktaskInsId)
        {
            CrmWorkFlowService.AuditMessage am = new CrmWorkFlowService.AuditMessage();
            am.AuditId = userID;
            am.WorkflowId = workflowId;
            am.WorkflowInsId = workflowInsId;
            am.WorktaskId = worktaskId;
            am.WorktaskInsId = worktaskInsId;
            am.OperatorInsId = operatorInsId;
            am.AuditUserName = userName;
            am.AuditArch = userDept;
            am.AuditDuty = userPost;
            am.Message = "";
            am.AuditResult = "";

            CrmWorkFlowService.WorkFlowServiceClient wfClient = new CrmWorkFlowService.WorkFlowServiceClient();
            wfClient.InsertAuditMessage(am);
        }

        #endregion
    }
}